package com.hellowx.qydcdev.interceptor;

import com.hellowx.qydcdev.annotaion.RequiredToken;
import com.hellowx.qydcdev.entity.User;
import com.hellowx.qydcdev.exception.CustomException;
import com.hellowx.qydcdev.exception.CustomExceptionType;
import com.hellowx.qydcdev.utils.RedisUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created on 2022/1/5.
 *  简单权限校验
 * @author Hello WX
 */
@Component("tokenInterceptor")
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
          如果类型为 HandlerMethod 则进行类型转换
          目的: 让 swagger 可以获取到接口信息
         */
        if (handler instanceof HandlerMethod){
            // 判断方法上是否有加 @RequiredToken 注解
            boolean requiredToken = ((HandlerMethod) handler).getMethod().isAnnotationPresent(RequiredToken.class);
            if (requiredToken){
                String token = request.getHeader("Token");
                boolean flag = redisUtils.hasKey(token);
                if (flag){
                    User user = (User) redisUtils.get(token);
                    request.setAttribute("loginUser",user);
                }else {
                    throw new CustomException(CustomExceptionType.PERMISSION_EXCEPTION,"权限不足!!");
                }
            }
        }
        return true;
    }
}
